import ToolHttpClient from "./ToolHttp";
import ToolRandom from "../ToolRandom";

export default {
	async menus() {
		let res = await ToolHttpClient.post("/action/action-table-infos/*");
		return buildMenus(res);
	}
}

function buildMenus(menus) {
	let parentMenus = [];
	if (!menus) return [];
	menus.forEach(({
		name,
		memo
	}) => {
		let memoSplit = memo.split("-");

		let nameSplit = name.split("_");
		let pName = nameSplit[0];
		let cName = name.substr(pName.length + 1);

		let pMenu = parentMenus.find(pItem => pItem.menu_id === pName);

		if (!pMenu) {
			parentMenus.push(pMenu = {
				icon: ToolRandom.randomIcon(),
				text: memoSplit[0] || pName,
				value: `/pages/common/index?code=${name}`,
				children: [],
				menu_id: pName
			});
		}
		parentMenus.push({
			icon: ToolRandom.randomIcon(),
			text: memoSplit[1] || cName || pName,
			value: `/pages/common/index?code=${name}`,
			menu_id: name,
			parent_id: pName
		})
	})
	return parentMenus;
}
